package de.gwtprime.client.login;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import de.gwtprime.client.PrimeService;
import de.gwtprime.client.PrimeServiceAsync;
import de.gwtprime.client.util.GWTUtils;
import de.gwtprime.client.viewsStatic.LoadingIndictator;
import de.gwtprime.client.widgets.helper.InfoPopup;
import de.gwtprime.shared.UserDTO;
import de.gwtprime.shared.util.AppUtilsShared;

public class ManualLoginContainer extends Composite {

	private static ManualLoginContainerUiBinder uiBinder = GWT
			.create(ManualLoginContainerUiBinder.class);

	interface ManualLoginContainerUiBinder extends
			UiBinder<Widget, ManualLoginContainer> {
	}

	@UiField Label emailInputLabel;
	@UiField Label passwordInputLabel;
	
	@UiField TextBox usernameInput;
	@UiField PasswordTextBox passwordInput;
	@UiField Button loginBtn;
	@UiField SimplePanel loadingIndicator;
	
	private HandlerRegistration passwordHandlerReg;
	private HandlerRegistration userNameHandlerReg;
	
	public ManualLoginContainer() {
		
		initWidget(uiBinder.createAndBindUi(this));
		
		emailInputLabel.setText(GWTUtils.I18n.loginEmailLbl());
		passwordInputLabel.setText(GWTUtils.I18n.loginPasswordLbl());
	
		usernameInput.getElement().setAttribute("placeholder", GWTUtils.I18n.loginEmailInputPlaceholder());
		passwordInput.getElement().setAttribute("placeholder", GWTUtils.I18n.loginPasswordInputPlaceholder());
		
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	usernameInput.setFocus(true);
	        }
	    });

		activateLogin();
		
		loginBtn.setText(GWTUtils.I18n.loginButton());
		loginBtn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				login();
			}
		});
		
		loadingIndicator.add(new LoadingIndictator(false));
	}
	
	private void login() {
		
		// Check for empty user name
		if(AppUtilsShared.isNullOrEmpty(usernameInput.getText())){
			new InfoPopup("Gib bitte einen gültigen Benutzer Namen ein").center();
			return;
		}
		
		// Check for empty password
		if(AppUtilsShared.isNullOrEmpty(passwordInput.getText())){
			new InfoPopup("Gib bitte einen gültiges Passwort ein").center();
			return;
		}
			
		deactivateLogin();
		
		PrimeServiceAsync async = GWT.create(PrimeService.class);
		
		async.login(usernameInput.getText(), passwordInput.getText(), new AsyncCallback<UserDTO>() {
			
			@Override
			public void onSuccess(UserDTO result) {
				
				if(result == null){
					new InfoPopup(GWTUtils.I18n.loginFailedMsg()).center();
					activateLogin();
					return;
				}
				
				Window.Location.assign("http://"+Window.Location.getHost()+Window.Location.getPath()+Window.Location.getQueryString());
			}
			
			@Override
			public void onFailure(Throwable caught) {
				new InfoPopup(GWTUtils.I18n.loginFailedMsgActivation()).center();
				activateLogin();
			}
		});
	}

	/**
	 * Deactivate the login mask during user check at the BE
	 */
	private void deactivateLogin() {
		usernameInput.setEnabled(false);
		passwordInput.setEnabled(false);
		loginBtn.setEnabled(false);
		loadingIndicator.removeStyleName("invisible");
		passwordHandlerReg.removeHandler();
		userNameHandlerReg.removeHandler();
	}
	
	/**
	 * Activate the login mask again
	 */
	private void activateLogin() {
		
		passwordHandlerReg = passwordInput.addKeyDownHandler(new KeyDownHandler() {

			@Override
			public void onKeyDown(KeyDownEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					login();
				}
			}
		});
		
		userNameHandlerReg = usernameInput.addKeyDownHandler(new KeyDownHandler() {

			@Override
			public void onKeyDown(KeyDownEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					login();
				}
			}
		});
		
		usernameInput.setEnabled(true);
		passwordInput.setEnabled(true);
		loginBtn.setEnabled(true);
		loadingIndicator.addStyleName("invisible");
	}

}
